<?php

namespace app\agent\service;

use app\api\service\CommonService;
use app\model\Agent;
use think\facade\Db;

class AgentFinance extends CommonService
{
    public $table = 'agent_finance_daily';
    /*
     从订单提取数据到日报表 transferDailyFinanceFromOrder
    fromDate 开始时间  2021-10-27 10：00：00
    endDate 结束时间
    */

    /**
     * @desperated
     * 财务对账 日报表最终查询sq
     */
    public function dailyFinanceSql($agentId = 0, $endDate, $fromDate = '')
    {
        $endDate .= ' 23:59:59';
        if ($fromDate) {
            $fromDate .= ' 00:00:00';
            $createdWhere = " and created_at between '{$fromDate}' and '{$endDate}'";
            $payTimeWhere = " and pay_time between '{$fromDate}' and '{$endDate}'";
            $refundWhere = " and refund_at between '{$fromDate}' and '{$endDate}'";
            $refundTimeWhere = " and refundtime between '{$fromDate}' and '{$endDate}'";
        } else {
            $createdWhere = " and created_at <='{$endDate}'";
            $payTimeWhere = " and pay_time <='{$endDate}'";
            $refundWhere = " and refund_at <='{$endDate}'";
            $refundTimeWhere = " and refundtime <='{$endDate}'";
        }

        if ($agentId) {
            $createdWhere .= " and agent_id ={$agentId}";
            $payTimeWhere .= " and agent_id ={$agentId}";
            $refundWhere .= " and agent_id ={$agentId}";
        }

        $sql = <<<sql
            (
                select 
                agent_id,
                SUBSTR(created_at, 1,10) as dateymd,
                sum(sale_price) as income,
                sum(settle_price) as payout,
                sum(profit) as profit,
                1 as serv_type,
                'order' as type
                from mobile_order 
                where order_from!=1 and `status`=2 {$createdWhere}
                GROUP BY agent_id,dateymd
            ) 
            union all             
            (
                select
                agent_id,
                SUBSTR(refund_at, 1,10) as dateymd,
                sum(0-sale_price) as income, 
                sum(0-settle_price) as payout, 
                sum(0-profit) as profit,
                1 as serv_type,
                'refund' as type
                from mobile_order            
                where order_from!=1 and `status`=2 and refund_status=3 {$refundWhere}
                GROUP BY agent_id,dateymd
            )
            union all 
            (
                select 
                agent_id,
                SUBSTR(pay_time, 1,10) as dateymd,
                sum(pay_amount) as income,
                sum(pay_amount-agent_profit) as payout,
                sum(agent_profit) as profit,
                2 as serv_type,
                'order' as type
                from oil_order 
                where `status` =1 {$payTimeWhere}
                GROUP BY agent_id,dateymd
            )
            union all 
            (
                select agent_id,
                SUBSTR(refund_at, 1,10) as dateymd,
                sum(0-pay_amount) as payout,
                sum(agent_profit-pay_amount) as payout,
                sum(0-agent_profit) as profit,
                2 as serv_type,
                'refund' as type
                from oil_order 
                where `status` =1  and refund_status=1 {$refundWhere}
                GROUP BY agent_id,dateymd
            )
            union all 
            (
                select agent_id,
                SUBSTR(created_at, 1,10) as dateymd,
                sum(sale_price) as income,
                sum(sale_price-profit) as payout,
                sum(profit) as profit,
                5 as serv_type,
                'order' as type
                from movie_order 
                where `status` =2 {$createdWhere}
                GROUP BY agent_id,dateymd
            )
            union all 
            (
                select agent_id,
                SUBSTR(refund_at, 1,10) as dateymd,
                sum(0-sale_price) as income,
                sum(profit-sale_price) as payout,
                sum(0-profit) as profit,
                5 as serv_type,
                'refund' as type
                from movie_order 
                where `status` =2  and refund_status=3 {$refundWhere}
                GROUP BY agent_id,dateymd
            ) 
            union all 
            (
                select agent_id,
                SUBSTR(created_at, 1,10) as dateymd,
                sum(payprice) as income,
                sum(payprice-profit) as payout,
                sum(profit) as profit,
                4 as serv_type,
                'order' as type
                from takeout_order 
                where `status` <>9 {$createdWhere}
                GROUP BY agent_id,dateymd
            )
            union all 
            (
                select agent_id,
                SUBSTR(refundtime, 1,10) as dateymd,
                sum(0-payprice) as payout,
                sum(profit-payprice) as income,
                sum(0-profit) as profit,
                4 as serv_type,
                'refund' as type
                from takeout_order 
                where `status`=9  {$refundTimeWhere}
                GROUP BY agent_id,dateymd
            )
sql;

        $similarStructTable = [
            'oil_card_order' => PRODUCT_OILCARD_SERV,
            'power_order' => PRODUCT_POWER_SERV,
            '`order`' => PRODUCT_COUPON_SERV,
        ];
        foreach ($similarStructTable as $table => $v) {
            $sql .= <<<sql
            union all 
            (
                select agent_id,
                SUBSTR(created_at, 1,10) as dateymd,
                sum(amount) as income,
                sum(amount-agent_profit) as payout,
                sum(agent_profit) as profit,
                {$v} as serv_type,
                'order' as type
                from {$table} 
                where `pay_status` =1 {$createdWhere}
                GROUP BY agent_id,dateymd
            )
            union all 
            (
                select agent_id,                
                SUBSTR(refund_at, 1,10) as dateymd,
                sum(0-amount) as income,
                sum(agent_profit-amount) as payout,
                sum(0-agent_profit) as profit,
                {$v} as serv_type,
                'refund' as type
                from {$table}  
                where `pay_status` =1  and refund_status=1 {$refundWhere}
                GROUP BY agent_id,dateymd
            )
sql;
        }

        return $sql;
    }

    /*
    todo 是否需要改动，当前直接copy 自 总后台明细的sql语句
    财务对账日报明细
    由于执行原生sql ，做好防注入
    param （由于查询字段对应数据库字段不一样，param只能固定取值）目前只能包含 []
    */
    /*
    财务对账日报明细
    由于执行原生sql ，做好防注入
    param （由于查询字段对应数据库字段不一样，param只能固定取值）目前只能包含 []
    */
    private function dayDetailSql($dateFrom, $dateEnd, $param)
    {
        $sqlModuleArr = [
            PRODUCT_MOBILE_SERV => [
                'order' => '',
                'refund' => '',
                'orderWhere' => [$dateFrom.' 00:00:00', $dateEnd.' 23:59:59'],
                'refundWhere' => [$dateFrom.' 00:00:00', $dateEnd.' 23:59:59'],
            ],
            PRODUCT_OIL_SERV => [
                'order' => '',
                'refund' => '',
                'orderWhere' => [$dateFrom.' 00:00:00', $dateEnd.' 23:59:59'],
                'refundWhere' => [$dateFrom.' 00:00:00', $dateEnd.' 23:59:59'],
            ],
            PRODUCT_FILM_SERV => [
                'order' => '',
                'refund' => '',
                'orderWhere' => [$dateFrom.' 00:00:00', $dateEnd.' 23:59:59'],
                'refundWhere' => [$dateFrom.' 00:00:00', $dateEnd.' 23:59:59'],
            ],
            PRODUCT_MEAL_SERV => [
                'order' => '',
                'refund' => '',
                'orderWhere' => [$dateFrom.' 00:00:00', $dateEnd.' 23:59:59'],
                'refundWhere' => [$dateFrom.' 00:00:00', $dateEnd.' 23:59:59'],
            ],
            PRODUCT_COUPON_SERV => [
                'order' => '',
                'refund' => '',
                'orderWhere' => [$dateFrom.' 00:00:00', $dateEnd.' 23:59:59'],
                'refundWhere' => [$dateFrom.' 00:00:00', $dateEnd.' 23:59:59'],
            ],
            PRODUCT_OILCARD_SERV => [
                'order' => '',
                'refund' => '',
                'orderWhere' => [$dateFrom.' 00:00:00', $dateEnd.' 23:59:59'],
                'refundWhere' => [$dateFrom.' 00:00:00', $dateEnd.' 23:59:59'],
            ],
            PRODUCT_POWER_SERV => [
                'order' => '',
                'refund' => '',
                'orderWhere' => [$dateFrom.' 00:00:00', $dateEnd.' 23:59:59'],
                'refundWhere' => [$dateFrom.' 00:00:00', $dateEnd.' 23:59:59'],
            ],
        ];

        // 话费订单
        $serType = PRODUCT_MOBILE_SERV;
        $sqlModuleArr[$serType]['order'] = <<<sql
        select ordert.sub_order_id as order_sn,
        ordert.amount,
        ordert.sale_price,
        ordert.profit as agent_profit,
        ordert.platform_profit as profit,
        ordert.supplier_price as supplier_price,
        ordert.agent_id,
        agent.company_name as company_name,
        ordert.mobile_supplier_id,
        supplier.`name` as supplier_name,
        ordert.settle_type as agent_settle_type,
        ordert.created_at as datetime,
        {$serType} as serv_type
        from mobile_order as ordert
        inner join mobile_supplier as supplier on ordert.mobile_supplier_id=supplier.id inner join agent on agent.id=ordert.agent_id
        WHERE	ordert.order_from != 1 AND ordert.`status` = 2 and ordert.created_at between ? and ?
sql;
        $sqlModuleArr[$serType]['refund'] = <<<sql
        select ordert.sub_order_id as order_sn,
        ordert.amount,
        (0-ordert.sale_price) as sale_price,
        (0-ordert.profit) as agent_profit,
        (0-ordert.platform_profit) as profit,
        (0-ordert.supplier_price) as supplier_price,
        ordert.agent_id,
        agent.company_name as company_name,
        ordert.mobile_supplier_id,
        supplier.`name` as supplier_name,
        ordert.settle_type as agent_settle_type,
        ordert.refund_at as datetime,
        {$serType} as serv_type
        from mobile_order as ordert
        inner join mobile_supplier as supplier on ordert.mobile_supplier_id=supplier.id inner join agent on agent.id=ordert.agent_id
        WHERE	ordert.order_from != 1 AND ordert.`status` = 2 AND ordert.refund_status = 3 and ordert.refund_at between ? and ?
sql;

        // 滴滴加油
        $serType = PRODUCT_OIL_SERV;
        $sqlModuleArr[$serType]['order'] = <<<sql
        select
        ordert.out_order_id as order_sn,
        ordert.pay_amount as amount,
        ordert.pay_amount as sale_price,
        ordert.agent_profit,
        ordert.profit,
        ordert.pay_amount as supplier_price,
        ordert.agent_id,
        agent.company_name as company_name,
        ordert.supplier_id,
        supplier.`name` as supplier_name,
        ordert.agent_settle_type ,
        ordert.pay_time as datetime,
        {$serType} as serv_type
        from
        oil_order as ordert inner join base_supplier as supplier on ordert.supplier_id=supplier.id inner join agent on agent.id=ordert.agent_id
        where ordert.`status` = 1 and ordert.pay_time between ? and ?
sql;
        $sqlModuleArr[$serType]['refund'] = <<<sql
        select
        ordert.out_order_id as order_sn,
        ordert.pay_amount as amount,
        (0-ordert.pay_amount) as sale_price,
        (0-ordert.agent_profit) as agent_profit,
        (0-ordert.profit) as profit,
        (0-ordert.pay_amount) as supplier_price,
        ordert.agent_id,
        agent.company_name as company_name,
        ordert.supplier_id,
        supplier.`name` as supplier_name,
        ordert.agent_settle_type ,
        ordert.refund_at as datetime,
        {$serType} as serv_type
        from
        oil_order as ordert inner join base_supplier as supplier on ordert.supplier_id=supplier.id inner join agent on agent.id=ordert.agent_id
        where ordert.`status` = 1 and ordert.refund_status=1 and ordert.refund_at between ? and ?
sql;
        //影票订单
        $serType = PRODUCT_FILM_SERV;
        $sqlModuleArr[$serType]['order'] = <<<sql
        select
        ordert.order_id as order_sn,
        ordert.sale_price as amount,
        ordert.sale_price,
        ordert.profit as agent_profit,
        (ordert.sale_price-ordert.profit-ordert.cost_price) as profit,
        ordert.cost_price as supplier_price,
        ordert.agent_id,
        agent.company_name as company_name,
        ordert.supplier_id,
        supplier.`name` as supplier_name,
        ordert.settle_type as agent_settle_type ,
        ordert.created_at as datetime,
        {$serType} as serv_type
        from
        movie_order as ordert inner join base_supplier as supplier on ordert.supplier_id=supplier.id inner join agent on agent.id=ordert.agent_id
        where ordert.`status` = 2 and ordert.created_at between ? and ?
sql;
        $sqlModuleArr[$serType]['refund'] = <<<sql
        select
        ordert.order_id as order_sn,
        ordert.sale_price as amount,
        (0-ordert.sale_price) as sale_price,
        (0-ordert.profit) as agent_profit,
        (ordert.cost_price+ordert.profit-ordert.sale_price) as profit,
        (0-ordert.cost_price) as supplier_price,
        ordert.agent_id,
        agent.company_name as company_name,
        ordert.supplier_id,
        supplier.`name` as supplier_name,
        ordert.settle_type as agent_settle_type ,
        ordert.refund_at as datetime,
        {$serType} as serv_type
        from
        movie_order as ordert inner join base_supplier as supplier on ordert.supplier_id=supplier.id inner join agent on agent.id=ordert.agent_id
        where ordert.`status` = 2 and ordert.refund_status=3 and ordert.refund_at between ? and ?
sql;
        //外卖订单
        $serType = PRODUCT_MEAL_SERV;
        $sqlModuleArr[$serType]['order'] = <<<sql
        select
        ordert.order_id as order_sn,
        ordert.payprice as amount,
        ordert.payprice as sale_price,
        ordert.profit as agent_profit,
        0 as profit,
        (ordert.payprice-ordert.profit) as supplier_price,
        ordert.agent_id,
        agent.company_name as company_name,
        ordert.supplier_id,
        supplier.`name` as supplier_name,
        1 as agent_settle_type ,
        ordert.paytime as datetime,
        {$serType} as serv_type
        from
        takeout_order as ordert inner join base_supplier as supplier on ordert.supplier_id=supplier.id inner join agent on agent.id=ordert.agent_id
        where ordert.paytime between ? and ?
sql;
        $sqlModuleArr[$serType]['refund'] = <<<sql
        select
        ordert.order_id as order_sn,
        ordert.payprice as amount,
        (0-ordert.payprice) as sale_price,
        (0-ordert.profit) as agent_profit,
        0 as profit,
        (ordert.profit-ordert.payprice) as supplier_price,
        ordert.agent_id,
        agent.company_name as company_name,
        ordert.supplier_id,
        supplier.`name` as supplier_name,
        1 as agent_settle_type ,
        ordert.refundtime as datetime,
        {$serType} as serv_type
        from
        takeout_order as ordert inner join base_supplier as supplier on ordert.supplier_id=supplier.id inner join agent on agent.id=ordert.agent_id
        where ordert.`status` = 9 and ordert.refundtime between ? and ?
sql;
        // 相似订单结构
        $similarStructTable = [
            PRODUCT_COUPON_SERV => '`order`',
            PRODUCT_OILCARD_SERV => 'oil_card_order',
            PRODUCT_POWER_SERV => 'power_order',
        ];
        foreach ($similarStructTable as $serType => $table) {
            $sqlModuleArr[$serType]['order'] = <<<sql
                select
                ordert.sn as order_sn,
                ordert.amount as amount,
                ordert.amount as sale_price,
                ordert.agent_profit,
                ordert.profit,
                (ordert.amount-ordert.profit) as supplier_price,
                ordert.agent_id,
                agent.company_name as company_name,
                ordert.supplier_id,
                supplier.`name` as supplier_name,
                ordert.agent_settle_type ,
                ordert.created_at as datetime,
                {$serType} as serv_type
                from
                {$table} as ordert inner join base_supplier as supplier on ordert.supplier_id=supplier.id inner join agent on agent.id=ordert.agent_id
                where ordert.`pay_status` = 1 and ordert.created_at between ? and ?
sql;
            $sqlModuleArr[$serType]['refund'] = <<<sql
                select
                ordert.sn as order_sn,
                ordert.amount as amount,
                (0-ordert.amount) as sale_price,
                (0-ordert.agent_profit) as agent_profit,
                (0-ordert.profit) as profit,
                (ordert.profit-ordert.amount) as supplier_price,
                ordert.agent_id,
                agent.company_name as company_name,
                ordert.supplier_id,
                supplier.`name` as supplier_name,
                ordert.agent_settle_type ,
                ordert.refund_at as datetime,
                {$serType} as serv_type
                from
                {$table} as ordert inner join base_supplier as supplier on ordert.supplier_id=supplier.id inner join agent on agent.id=ordert.agent_id
                where ordert.`pay_status` = 1 and refund_status=1  and ordert.refund_at between ? and ?
sql;
        }

        // 单独某个类型订单
        if ($param) {
            if (!empty($param['supplier_id'])) {
                foreach ($sqlModuleArr as $k => $v) {
                    if (PRODUCT_MOBILE_SERV == $k) {
                        $sqlModuleArr[$k]['order'] .= ' and ordert.mobile_supplier_id=?';
                        $sqlModuleArr[$k]['refund'] .= ' and ordert.mobile_supplier_id=?';
                        $sqlModuleArr[$k]['orderWhere'][] = $param['supplier_id'];
                        $sqlModuleArr[$k]['refundWhere'][] = $param['supplier_id'];
                    } else {
                        $sqlModuleArr[$k]['order'] .= ' and ordert.supplier_id=?';
                        $sqlModuleArr[$k]['refund'] .= ' and ordert.supplier_id=?';
                        $sqlModuleArr[$k]['orderWhere'][] = $param['supplier_id'];
                        $sqlModuleArr[$k]['refundWhere'][] = $param['supplier_id'];
                    }
                }
            }
            if (!empty($param['agent_id'])) { // 代理商后续订单应该都是统一用 agent_id ,此处循环处理
                foreach ($sqlModuleArr as $k => $v) {
                    $sqlModuleArr[$k]['order'] .= ' and ordert.agent_id=?';
                    $sqlModuleArr[$k]['refund'] .= ' and ordert.agent_id=?';
                    $sqlModuleArr[$k]['orderWhere'][] = $param['agent_id'];
                    $sqlModuleArr[$k]['refundWhere'][] = $param['agent_id'];
                }
            }
        }

        return $sqlModuleArr;
    }

    /*
     数据迁移到日报表
    */
    public function insertAgentDailyFinanceFromOrder($endDate = '', $fromDate = '')
    {
        if (!$endDate) {
            $endDate = date('Y-m-d', strtotime('-1 day'));
        }
        if (substr($endDate, 0, 10) == date('Y-m-d')) {
            return $this->inValiReturn('不能迁移今天的数据');
        }

        $sql = 'select agent_id,dateymd,sum(temp.income) as income,sum(temp.payout) as payout,sum(temp.profit) as profit from ('.$this->dailyFinanceSql(0, $endDate, $fromDate).' ) as temp group by dateymd,agent_id';

        $sql = 'insert into '.$this->table.' (agent_id,dateymd,income,payout,profit) '.$sql;

        doLog($sql);

        try {
            $res = Db::execute($sql);

            return $this->valiReturn('成功insert'.$res.'条数据');
        } catch (\Exception $e) {
            doLog(getExceptionMsg($e));

            return $this->inValiReturn(getExceptionMsg($e));
        }
    }

    /*
     查询日报数据
     今天 实时查询
     今天之前的数据查询 agent_finance_daily
     dateFrom 开始日期
     endFrom 结束日期
     paginate 分页相关 [page=>1 , list_rows=>10]
     getSum 是否统计累计数据
    */
    public function getAgentFinanceDaily(int $agentId, string $dateFrom, string $dateEnd = '', array $paginate = [], $getSum = 0)
    {
        $dateYmd = date('Y-m-d');
        // 处理时间参数，防止直接从用户提交做查询
        if ($dateFrom) {
            $dateFrom = date('Y-m-d', strtotime($dateFrom.' 00:00:00'));
        }

        if (!$dateEnd) {
            $dateEnd = $dateYmd;
        }
        $dateEnd = date('Y-m-d', strtotime($dateEnd.' 00:00:00'));
        if ($dateEnd < $dateFrom) {
            $dateFrom = $dateEnd;
        }
        // todo 定时尚未吧数据迁移到 agent_finance_daily 时候订单实时查询

        $realTimeFrom = '';
        $dataSource = 1; // 1只从 agent_finance_daily 查询 2，只从实时查询 3，1+2的情况
        if ($dateEnd >= $dateYmd && $dateFrom <= $dateYmd) { // 包含今天
            if (0 == date('G') && (date('i')) < 20) { // 00：20之前操作查询，则昨天数据仍然实时查询
                $realTimeFrom = date('Y-m-d', strtotime('-1 day'));
            } else {
                $realTimeFrom = $dateYmd;
            }
            if ($realTimeFrom > $dateFrom) { // 此时是两张表union查询
                $dataSource = 3;
            } else {
                $dataSource = 2;
            }
        } elseif ($dateEnd < $dateYmd) {
            if ($dateEnd == date('Y-m-d', strtotime('-1 day'))) {
                if (0 == date('G') && (date('i')) < 20) { // 00：20之前操作查询，则昨天数据仍然实时查询
                    $realTimeFrom = date('Y-m-d', strtotime('-1 day'));
                    $dataSource = 3;
                } else {
                    $dataSource = 1;
                }
            } else {
                $dataSource = 1;
            }
        }

        //halt($dateFrom, $dateEnd, $realTimeFrom, $dataSource);

        $sql = '';
        $limit = '';
        $orderBy = ' order by dateymd desc ';
        $dailyField = 'agent_id,dateymd,income,payout,profit';
        if ($getSum) {
            $sumField = ',sum(income) as income,sum(payout) as payout,sum(profit) as profit';
        } else {
            $sumField = '';
        }
        // 分页参数
        if ($paginate) {
            if (empty($paginate['page'])) {
                $paginate['page'] = 1;
            }
            if (empty($paginate['list_rows'])) {
                $paginate['list_rows'] = 10;
            }
            $paginate['page'] = intval($paginate['page']);
            $paginate['list_rows'] = intval($paginate['list_rows']);

            $limit = ' limit '.(($paginate['page'] - 1) * $paginate['list_rows']).','.$paginate['list_rows'];
        }
        switch ($dataSource) {
            case 1:
                if ($dateFrom && $dateEnd) {
                    $sql = "select %s from {$this->table} where dateymd between '{$dateFrom}' and '{$dateEnd}' and agent_id={$agentId} {$orderBy}";
                } elseif ($dateFrom && !$dateEnd) {
                    $sql = "select %s from {$this->table} where dateymd >= '{$dateFrom}' {$orderBy} and agent_id={$agentId} {$orderBy} ";
                } elseif (!$dateFrom && $dateEnd) {
                    $sql = "select %s from {$this->table} where dateymd <= '{$dateEnd}' {$orderBy} and agent_id={$agentId} {$orderBy} ";
                } else {
                    $sql = "select %s from {$this->table} and agent_id={$agentId}  {$orderBy}";
                }

                if ($paginate) {
                    $list['total'] = Db::query(sprintf($sql, 'count(1) as total'.$sumField));
                } elseif ($getSum) {
                    $list['total'] = Db::query(sprintf($sql, trim($sumField, ',')));
                }
                $list['data'] = Db::query(sprintf($sql, $dailyField).$limit);

            break;
            case 2:
                $sql = $this->dailyFinanceSql($agentId, $dateEnd, $realTimeFrom);
                if ($paginate) {
                    $list['total'] = Db::query('select count(1) as total '.$sumField.' from ('.$sql.') as temp');
                } elseif ($getSum) {
                    $list['total'] = Db::query('select '.trim($sumField, ',').' from ('.$sql.') as temp');
                }

                $list['data'] = Db::query($sql.$orderBy.$limit);
            break;
            case 3:
                $sql = ''.$this->dailyFinanceSql($agentId, $dateEnd, $realTimeFrom);
                $sql .= ' union all (';
                if ($dateFrom && $dateEnd) {
                    $sql .= "select {$dailyField} from {$this->table} where dateymd between '{$dateFrom}' and '{$dateEnd}' and agent_id={$agentId} {$orderBy}";
                } elseif ($dateFrom && !$dateEnd) {
                    $sql .= "select {$dailyField} from {$this->table} where dateymd >= '{$dateFrom}' and agent_id={$agentId}  {$orderBy}";
                } elseif (!$dateFrom && $dateEnd) {
                    $sql .= "select {$dailyField} from {$this->table} where dateymd <= '{$dateEnd}' and agent_id={$agentId}  {$orderBy}";
                } else {
                    $sql .= "select {$dailyField}  from {$this->table} and agent_id={$agentId}  {$orderBy}";
                }
                $sql .= ')';
                $list['data'] = Db::query($sql.$orderBy.$limit);
                if ($paginate) {
                    $list['total'] = Db::query('select count(1) as total '.$sumField.' from ('.$sql.') as temp');
                } elseif ($getSum) {
                    $list['total'] = Db::query('select '.trim($sumField, ',').' from ('.$sql.') as temp');
                }
            break;
        }

        if ($getSum) {
            $list['sum'] = $list['total'][0];
        }

        if ($paginate) {
            if (isset($list['total']) && $list['total']) {
                $list['total'] = $list['total'][0]['total'];
            } else {
                $list['total'] = 0;
            }
            if (isset($list['total']) && $list['data']) {
            } else {
                $list['total'] = [];
            }
            $list['per_page'] = $paginate['list_rows'];
            $list['current_page'] = $paginate['page'];
            if ($list['total']) {
                $list['last_page'] = ceil($list['total'] / $paginate['list_rows']);
            } else {
                $list['last_page'] = 1;
            }
        }

        return $list;
    }

    /*
     获取某天明细记录
     dateYmd 具体日期
     param 查询参数
     servType 业务类型
     paginate 分页相关
     order 排序
     getSum 是否统计累计数据
    */
    public function daliyDetailList($dateFrom, $dateEnd, $param = [], $servType = '', $paginate = [], $getSum = 0, $order = ' order by datetime desc ')
    {
        // 构造sql
        $sqlArr = $this->dayDetailSql($dateFrom, $dateEnd, $param);

        $list = [
            'data' => [],
            'sum' => [],
            'total' => 0,
            'last_page' => 1,
            'current_page' => $paginate['page'] ?? 1,
            'page' => $paginate['page'] ?? 1,
            'list_rows' => $paginate['page'] ?? 0,
        ];
        $sql = '';
        $bindParam = [];
        foreach ($sqlArr as $k => $v) {
            if ($servType && $k != $servType) {
                continue;
            }
            $sql .= ' ('.$v['order'].') union all';
            if ($v['orderWhere']) {
                foreach ($v['orderWhere'] as $k2 => $v2) {
                    array_push($bindParam, $v2);
                }
            }
            $sql .= ' ('.$v['refund'].') union all';
            if ($v['refundWhere']) {
                foreach ($v['refundWhere'] as $k2 => $v2) {
                    array_push($bindParam, $v2);
                }
            }
        }
        // 去除最后一个union all
        $sql = trim($sql, 'union all');
        if (!$sql) {
            return $list;
        }

        if ($getSum) {
            $sumField = ',sum(agent_profit) as agent_profit';
        } else {
            $sumField = '';
        }

        doLog(' select count(1) as total '.$sumField.' from ('.$sql.') as temp');

        if ($paginate) {
            $list['total'] = Db::query(' select count(1) as total '.$sumField.' from ('.$sql.') as temp', $bindParam);
        } elseif ($getSum) {
            $list['total'] = Db::query(' select  '.trim($sumField, ',').' from ('.$sql.') as temp', $bindParam);
        }

        // 累计数据
        if ($getSum) {
            $list['sum'] = $list['total'][0];
        }

        // 查询列表
        $sql .= ' '.$order;
        $limit = '';

        // 分页参数
        if ($paginate) {
            if (empty($paginate['page'])) {
                $paginate['page'] = 1;
            }
            if (empty($paginate['list_rows'])) {
                $paginate['list_rows'] = 10;
            }
            $paginate['page'] = intval($paginate['page']);
            $paginate['list_rows'] = intval($paginate['list_rows']);

            $limit = ' limit '.(($paginate['page'] - 1) * $paginate['list_rows']).','.$paginate['list_rows'];
        }

        $sql .= ' '.$limit;
        $list['data'] = Db::query($sql, $bindParam);

        if ($paginate) {
            $list['per_page'] = $paginate['list_rows'];
            $list['current_page'] = $paginate['page'];
            if (!$list['total']) {
                $list['total'] = 0;
            } else {
                $list['total'] = $list['total'][0]['total'];
            }

            if ($list['total']) {
                $list['last_page'] = ceil($list['total'] / $paginate['list_rows']);
            } else {
                $list['last_page'] = 1;
            }
        }

        // 处理数据
        //$moneyCols = ['amount','sale_price','supplier_price','profit','agent_price'];
        $agentSettleType = Agent::$settleType;
        foreach ($list['data'] as $k => $v) {
            // 先处理平台利润 再处理其他金额字段
            $list['data'][$k]['profit'] = fen2yuan($v['profit']);
            $list['data'][$k]['amount'] = fen2yuan($v['amount']);
            $list['data'][$k]['sale_price'] = fen2yuan($v['sale_price']);
            $list['data'][$k]['supplier_price'] = fen2yuan($v['supplier_price']);
            //$list['data'][$k]['agent_price'] = fen2yuan($v['agent_price']);
            //  代理商结算类型
            $list['data'][$k]['agent_settle_type'] = $agentSettleType[$v['agent_settle_type']] ?? $v['agent_settle_type'];
            $list['data'][$k]['serv_type_name'] = PRODUCT_SERV_TYPE[$v['serv_type']]['orderName'] ?? $v['serv_type'];
        }

        return $list;
    }
}
